<template>
  <div class="my-posts-page">
    <NavBar />
    
    <div class="main-content">
      <div class="container">
        <div class="page-header">
          <h1 class="page-title">我的博客</h1>
          <p class="page-subtitle">管理您的文章和草稿</p>
        </div>

        <!-- 统计信息 -->
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-number">{{ totalPosts }}</div>
            <div class="stat-label">总文章数</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ publishedPosts }}</div>
            <div class="stat-label">已发布</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ draftPosts }}</div>
            <div class="stat-label">草稿</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ totalViews }}</div>
            <div class="stat-label">总浏览量</div>
          </div>
        </div>

        <!-- 筛选和操作栏 -->
        <div class="filter-bar">
          <div class="filter-left">
            <el-radio-group v-model="statusFilter" @change="handleStatusFilter">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="published">已发布</el-radio-button>
              <el-radio-button label="draft">草稿</el-radio-button>
            </el-radio-group>
          </div>
          <div class="filter-right">
            <el-button type="primary" @click="$router.push('/write')">
              <el-icon><Edit /></el-icon>
              写新文章
            </el-button>
          </div>
        </div>

        <!-- 文章列表 -->
        <div class="posts-list" v-loading="loading">
          <div v-if="filteredPosts.length === 0" class="empty-state">
            <el-empty description="暂无文章">
              <el-button type="primary" @click="$router.push('/write')">
                开始写作
              </el-button>
            </el-empty>
          </div>
          
          <div v-else class="posts-grid">
            <div 
              v-for="post in filteredPosts" 
              :key="post.id" 
              class="post-card"
              @click="viewPost(post)"
            >
              <div class="post-cover" v-if="post.cover_image">
                <img :src="post.cover_image" :alt="post.title" />
              </div>
              <div class="post-content">
                <h3 class="post-title">{{ post.title }}</h3>
                <p class="post-excerpt">{{ post.excerpt || '暂无摘要' }}</p>
                <div class="post-meta">
                  <div class="post-stats">
                    <span class="stat-item">
                      <el-icon><View /></el-icon>
                      {{ post.view_count }}
                    </span>
                    <span class="stat-item">
                      <el-icon><Star /></el-icon>
                      {{ post.like_count }}
                    </span>
                  </div>
                  <div class="post-status">
                    <el-tag :type="post.is_published ? 'success' : 'warning'">
                      {{ post.is_published ? '已发布' : '草稿' }}
                    </el-tag>
                  </div>
                </div>
                <div class="post-actions">
                  <el-button 
                    size="small" 
                    @click.stop="editPost(post)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click.stop="deletePost(post)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="totalPages > 1">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="totalPosts"
            layout="prev, pager, next, total"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import NavBar from '@/components/NavBar.vue'
import Footer from '@/components/Footer.vue'
import type { Post } from '@/types'
import api from '@/utils/api'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const posts = ref<Post[]>([])
const loading = ref(false)
const statusFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(12)

// 计算属性
const totalPosts = computed(() => posts.value.length)
const publishedPosts = computed(() => posts.value.filter(p => p.is_published).length)
const draftPosts = computed(() => posts.value.filter(p => !p.is_published).length)
const totalViews = computed(() => posts.value.reduce((sum, p) => sum + p.view_count, 0))

const filteredPosts = computed(() => {
  let filtered = posts.value
  
  if (statusFilter.value === 'published') {
    filtered = filtered.filter(p => p.is_published)
  } else if (statusFilter.value === 'draft') {
    filtered = filtered.filter(p => !p.is_published)
  }
  
  return filtered
})

const totalPages = computed(() => Math.ceil(totalPosts.value / pageSize.value))

// 方法
const fetchMyPosts = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  try {
    loading.value = true
    const response = await api.get<Post[]>('/posts/my-posts')
    posts.value = response.data
  } catch (error) {
    console.error('获取我的文章失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

const handleStatusFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  // 这里可以实现分页加载逻辑
}

const viewPost = (post: Post) => {
  router.push(`/posts/${post.id}`)
}

const editPost = (post: Post) => {
  router.push(`/edit/${post.id}`)
}

const deletePost = async (post: Post) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文章"${post.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await api.delete(`/posts/${post.id}`)
    ElMessage.success('文章删除成功')
    await fetchMyPosts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除文章失败')
    }
  }
}

// 生命周期
onMounted(() => {
  fetchMyPosts()
})
</script>

<style scoped>
.my-posts-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #333;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  color: #666;
  font-size: 1.1rem;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: white;
  padding: 1.5rem;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 0.5rem;
}

.stat-label {
  color: #666;
  font-size: 0.9rem;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  background: white;
  padding: 1rem 1.5rem;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.posts-list {
  margin-bottom: 2rem;
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 3rem;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.posts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
}

.post-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.post-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.post-cover {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.post-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.post-content {
  padding: 1.5rem;
}

.post-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.75rem;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-excerpt {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
  margin-bottom: 1rem;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.post-stats {
  display: flex;
  gap: 1rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  color: #666;
  font-size: 0.85rem;
}

.post-actions {
  display: flex;
  gap: 0.5rem;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
  }
  
  .filter-bar {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .posts-grid {
    grid-template-columns: 1fr;
  }
}
</style>
